import socket
import threading

# 服务器配置
HOST = '127.0.0.1'
PORT = 12345

# 选择昵称
nickname = input("请输入你的昵称: ")

# 创建客户端套接字
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

# 接收服务器消息
def receive():
    while True:
        try:
            message = client.recv(1024).decode('utf-8')
            if message == 'NICK':
                client.send(nickname.encode('utf-8'))
            else:
                print(message)
        except:
            print("发生错误，退出聊天！")
            client.close()
            break

# 发送消息给服务器
def write():
    while True:
        message = f'{nickname}: {input("")}'
        client.send(message.encode('utf-8'))

# 创建接收和发送线程
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()    
